package com.tzraeq.ant.ext.freemarker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.tools.ant.Task;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerTask extends Task {
	
	private String destPath;
	
	private String templatePath;
	
	public void execute(){
		Configuration cfg = new Configuration(Configuration.getVersion());
		Map properties = getProject().getProperties();
		String basedir = properties.get("basedir").toString();
		File templateFile = new File(basedir,templatePath);
		File destFile = new File(basedir,destPath);
		try {
			cfg.setDirectoryForTemplateLoading(templateFile.getAbsoluteFile().getParentFile());
			Template template = cfg.getTemplate(templateFile.getName());
	        Writer out = new OutputStreamWriter(new FileOutputStream(destFile));  
	        Map root = new HashMap();
	        root.put("properties", properties);
	        template.process(root, out);
	        out.flush(); 
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	private Map wrapMap(Map table){
		Map map = new HashMap();
		for (Iterator it = table.entrySet().iterator(); it.hasNext();)
	    {
	      Map.Entry entry = (Map.Entry)it.next();
	      map.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
	    }
		return map;
	}
	
	public void setTemplate(String path){
		templatePath = path;
	}
	
	public void setDest(String path){
		destPath = path;
	}
}
